#!/usr/bin/python3
import datetime

import requests
import time
from tqdm import tqdm
import db
from db import OneAutoPunch
from exceptions import exception_handler, TokenExpire
from log import logger
from message import send_private_msg


def punch_specific_one(punch_record: OneAutoPunch):
    """
    打卡操作
    :param punch_record
    :return:
    """
    sess = requests.session()
    sess.headers = {"User-Agent": "Mozilla/5.0 (Linux; Android 7.1.1; MI 6 Build/NMF26X; wv) "
                                  "AppleWebKit/537.36 (KHTML, like Gecko) "
                                  "Version/4.0 Chrome/57.0.2987.132 MQQBrowser/6.2 TBS/043807 Mobile Safari/537.36 "
                                  "MicroMessenger/6.6.1.1220(0x26060135) NetType/4G Language/zh_CN "
                                  "MicroMessenger/6.6.1.1220(0x26060135) NetType/4G Language/zh_CN miniProgram",
                    "ncov-access-token": punch_record.auto_punch_token}
    res = sess.get("https://www.ioteams.com/ncov/api/users/last-report")
    last_report = res.json()['data']['data']
    new_report = {}
    # 使用上一次的打卡记录
    for key in ['address', 'self_suspected', 'self_confirmed', 'family_suspected', 'family_confirmed', 'fever',
                'infected', 'description', 'at_home', 'contacted', 'passed_beijing', 'contacted_beijing']:
        new_report.update({key: last_report[key]})
    del new_report['address']['_id']
    # 进行打卡
    res = sess.post("https://www.ioteams.com/ncov/api/users/dailyReport", json=new_report)
    try:
        if res.status_code == 200 and res.json()['code'] == 0:
            logger.info(f"{punch_record.comment}: status_code:{res.status_code} {res.text}")
        else:
            # 输出失败日志
            logger.warn(f"{punch_record.comment}: status_coe:{res.status_code} {res.text}")
    except Exception as e:
        logger.warn(e.args, e.with_traceback())
        # 打卡失败后，抛出异常
        raise TokenExpire()
    return res.json()['msg']


@exception_handler
def auto_punch():
    """
    小one易自动打卡
    """
    # 查询所有打卡记录
    for auto_punch_record in tqdm(db.session.query(OneAutoPunch).filter(OneAutoPunch.skip == '否').all()):
        time.sleep(1)
        auto_punch_record: OneAutoPunch
        try:
            resp = punch_specific_one(auto_punch_record)
            if auto_punch_record.complete_msg == '是' and auto_punch_record.qq is not None:
                # 发送消息
                send_private_msg(auto_punch_record.qq,
                                 datetime.datetime.now().strftime('%Y-%m-%d') + '：今日易统计打卡完毕')
            logger.info('\n%-6s' % auto_punch_record.comment + resp)
        except TokenExpire as e:
            logger.warn('\n%-6s' % auto_punch_record.comment + str(e))
            try:
                # 发送消息
                logger.warn(auto_punch_record.comment + '打卡登录过期')
                send_private_msg(auto_punch_record.qq, '易统计打卡登录过期，今日请手动完成打卡')
            except Exception as e:
                logger.warn(e.args, e.with_traceback())
        except Exception as e:
            logger.warn(e)
